<template>
  <!--商品详情页-->
  <div class="productDetail">

    <!--分享-->
    <van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" />
    <!--轮播图-->
    <van-swipe autoplay="3000" style="height:350px;">
      <van-swipe-item>
        <van-image width="100%" height="3.5rem" :src="$baseUrl + productDetail.cover.slice(2)" style="height:350px;" />
      </van-swipe-item>
    </van-swipe>
    <Tips />
    <!--简单描述信息-->
    <div class="info">
      <h2>{{productDetail.name}}</h2>
      <p>{{productDetail.intro}}</p>
      <p class="price">￥{{productDetail.price}}元</p>
    </div>
    <!-- 展示弹出层 -->
    <br>
    <van-cell title="查看规格" is-link @click="show=true" />

    <van-cell :title="'用户评论(' + commentList.length + ')'" is-link style="max-height:300px;overflow:hidden;overflow-y:scroll;">
      <template #label v-if="commentList.length>0">
        <div class="comment-card" v-for="(item,index) in commentList" :key="index">
        <div class="top" style="display:flex;justify-content: space-between;">
          <div style="display:flex;align-items:center;">
            <img :src="$baseUrl + item.avatar" alt="" style="height:30px;width:30px;border-radius:50%;">
            <div style="margin: 0 5px;">{{item.username}}</div>
            <van-rate v-model="item.rate"/>
          </div>
          <div style="line-height:30px;">{{item.createTime}}</div>
        </div>
        <div class="content" style="margin-top:5px;">
          {{item.content}}
        </div>
    </div>
      </template>

      <template #label v-else> 
        <div>暂未有人评价，你来当大冤种吧~</div>
      </template>
    </van-cell>
    
    <!--相关产品列表-->
    <div class="about" v-if="productList.length>0">
      <van-divider>大家都在看</van-divider>
      <product-list :productList="productList"></product-list>
    </div>
    <!-- sku -->
    <van-sku v-model="show" ref="sku" :sku="sku" :goods="goods" :hide-stock="sku.hide_stock" @buy-clicked="onBuyClicked"
      @add-cart="addToCart" />
    <MyGoodsActions ref="MyGoodsActions" @addToCart="addToCart" :badge="badge" :goodsId="productDetail.id" />

    <GoTopVue ref="goTop"></GoTopVue>
  </div>
</template>

<script>
import Tips from "../components/productDetail/Tips";
import MyGoodsActions from "../components/productDetail/MyGoodsActions";
import ProductList from '../components/product/ProductList.vue';
import GoTopVue from "../components/common/GoTop.vue";
import { getCategoryGoodsList, getProductById, firstAddCollect, addUpdate, pay, addOrder, selectAllCollectGoods, selectCommentByGoodsId } from '../request/api'
export default {
  name: "ProductDetail",
  components: { Tips, MyGoodsActions, ProductList, GoTopVue },
  data() {
    return {
      commentList:[],
      //显示sku
      show: false,
      sku: {
        tree: [],
        hide_stock: false,
        price: 0,
        stock_num: 227,
      },
      goods: {
        picture: "",
      },
      messageConfig: {},
      //是否显示分享
      showShare: false,
      options: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' },
        ],
        [
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' },
        ]],
      productList: [],
      badge: 0,
      productDetail: {},
    }
  },
  mounted() {
    this.init()
  },
  watch: {
    "$route": function (to, from) {
      this.init()
      this.$refs.goTop.goTop()
    }
  },


  methods: {
    init() {
      getProductById(this.$route.query.productId).then(res => {
        this.productDetail = res.data
        this.goods.picture = this.$baseUrl + res.data.cover.slice(2)
        this.sku.price = res.data.price
      })
      this.$bus.$on('changeShowShare', () => {
        this.showShare = !this.showShare
      })
      setTimeout(() => {
        this.getProductList()
        this.getCollectGoodsIdList()
      }, 350)
      selectCommentByGoodsId(this.$route.query.productId).then(res => {
        this.commentList = res.data
      })

    },
    getCollectGoodsIdList() {
      if (localStorage.getItem('token')) {
        selectAllCollectGoods({ id: JSON.parse(localStorage.getItem('userInfo')).id }).then(res => {
          if (res.data) {
            res.data.forEach(item => {
              if (item.id == this.productDetail.id) this.$nextTick(() => {
                this.$refs.MyGoodsActions.isCollect = true
              })
            })
          }
        })
      }
    },
    onBuyClicked() {
      if (localStorage.getItem('token')) {
        let userId = localStorage.getItem('userId')
        let price = this.sku.price
        pay({ userId, price }).then(res => {
          if (res.data) {
            this.$toast.success(res.message)
            let data = {
              userId,
              status: 0,
              goodsIdList: null,
              goodsId: this.productDetail.id
            }
            addOrder(data).then(res => {
              if (res.data) {
                this.$toast.success(res.message)
                this.show = false
              }
            })
          } else {
            this.$dialog.confirm({
              title: '余额不足',
              message: '前去充值!'
            }).then(() => {
              this.$router.push('/recharge')
            }).catch(() => {
            })
          }
        })
      } else {
        this.$toast.fail('请先登录')
      }
    },
    back() {
      this.$router.back()
    },
    addToCart() {
      if (localStorage.getItem('token')) {
        this.$store.state.cartList.push(this.productDetail.id)
        this.$store.state.cartList = [...new Set(this.$store.state.cartList)]
        localStorage.setItem('cartList', JSON.stringify(this.$store.state.cartList))
        let data = {
          userId: localStorage.getItem('userId'),
          cartInfo: JSON.stringify(this.$store.state.cartList)
        }
        this.$store.state.isNewUser = JSON.parse(localStorage.getItem('isNewUser'))
        if (this.$store.state.isNewUser) {
          firstAddCollect(data).then(res => {
            this.$toast.success(res.message)
            this.$store.state.isNewUser = false
            localStorage.setItem('isNewUser', false)
          })
        } else {
          addUpdate(data).then(res => {
            this.$toast.success(res.message)
          })
        }
      } else {
        this.$toast.fail('请先登录!')
      }
    },
    getProductList() {
      getCategoryGoodsList({ id: this.productDetail.categoryId }).then(res => {
        this.productList = res.data
      })
    }
  },


}
</script>

<style scoped>
.productDetail {
  margin-top: 46px;
}

.van-goods-action {
  z-index: 9999;
}


.box p {
  margin: 0;
  padding: 0;
}

.box img {
  width: 100%;
  height: 100%;
  display: block;
}

.top_bar {
  position: relative;
  background: #fff;
  height: 35px;
  z-index: 99;
  top: 0;
  left: 0;
  width: 100vw;
  overflow: hidden;
}

.info {
  background: white;
  text-align: center;


}

.price {
  font-weight: bold;
  color: red;
}

.attribute {
  margin: .1rem;
}

.attribute li {
  padding: .05rem;
  margin-top: .05rem;
  background: #DCDCDC;


}

.attribute span {
  margin-left: .1rem;
}


.issue li {
  margin: .05rem;
  line-height: .2rem;
}

.issue .question {
  font-weight: bold;
}

.issue .answer {
  text-indent: .2rem;
}

.van-divider {
  font-weight: bold;
  color: black;
  border-color: #DCDCDC;
  padding: 0 1rem;
}

/*设置前后的线条粗细*/
.van-divider::after,
.van-divider::before {
  border-width: .02rem;
}

.sku_desc h4 {
  margin-left: .3rem;
}

.sku_desc .van-tag {
  color: black;
  margin-left: .5rem;
  padding: .05rem;
}

.about {
  padding-bottom: .8rem;
}
</style>